package com.spzx.payment.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.security.annotation.RequiresLogin;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.service.AlipayService;
import com.spzx.payment.service.PaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @ClassName AlipayController
 * @Author 波
 * @Date 2024/8/16 15:55
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController extends BaseController {
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentInfoService paymentInfoService;

    @Operation(summary = "支付宝下单")
    @RequiresLogin
    @RequestMapping("submitAlipay/{orderNo}")
    @ResponseBody
    public AjaxResult submitAlipay(@PathVariable(value = "orderNo") String orderNo) {
        String form = alipayService.submitAlipay(orderNo);
        return success(form);
    }

    /**
     * 支付宝同步回调
     *
     * @return
     */
    @RequestMapping("callback/return")
    public String callBack() {
        // 同步回调给用户展示信息
        return "redirect:" + AlipayConfig.return_order_url;
    }

    @SneakyThrows
    @RequestMapping("callback/notify")
    @ResponseBody
    public String alipayNotify(@RequestParam Map<String, String> paramMap, HttpServletRequest request) {
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(paramMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        if (signVerified) {
            if(paramMap.get("trade_status").equals("TRADE_SUCCESS")||paramMap.get("trade_status").equals("TRADE_FINISHED")){
                //更改支付订单状态
                paymentInfoService.updatePaymentInfoStatus(paramMap);
            }
            return "success";
        } else {
            return "failure";
        }
    }

}
